<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * 输出信息到控制台
     */
    protected function info($message): void
    {
        if (isset($this->command)) {
            $this->command->info($message);
        } else {
            // 直接输出到控制台
            echo "\033[32m" . $message . "\033[0m" . PHP_EOL;
        }
    }
    
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        $this->createAdminTable();
        $this->createRolesTable();
        $this->createPermissionsTable();
        $this->createRolePermissionsTable();
        $this->createRoleUsersTable();
        $this->createSessionsTable();
    }

    /**
     * 创建管理员表
     */
    protected function createAdminTable(): void
    {
        $tableName = 'admin';
        $startTime = microtime(true);
        
        if (Schema::hasTable($tableName)) {
            $this->info("表 [{$tableName}] 已存在，跳过创建");
            return;
        }
        
        $this->info("正在创建 [{$tableName}] 表...");
        
        Schema::create($tableName, function (Blueprint $table) {
            $table->id();
            $table->string('username', 50)->unique()->comment('用户名');
            $table->string('password', 255)->comment('密码');
            $table->string('salt', 32)->nullable()->comment('密码盐');
            $table->string('nickname', 50)->nullable()->comment('昵称');
            $table->timestamp('last_login_time')->nullable()->comment('最后登录时间');
            $table->string('last_login_ip', 45)->nullable()->comment('最后登录IP');
            $table->tinyInteger('status')->default(1)->comment('状态 0:禁用 1:启用');
            $table->timestamps();
            $table->softDeletes();
        });
        
        $endTime = microtime(true);
        $executionTime = round($endTime - $startTime, 2);
        $this->info("表 [{$tableName}] 创建完成，用时: {$executionTime}秒");
    }

    /**
     * 创建角色表
     */
    protected function createRolesTable(): void
    {
        $tableName = 'admin_roles';
        $startTime = microtime(true);
        
        if (Schema::hasTable($tableName)) {
            $this->info("表 [{$tableName}] 已存在，跳过创建");
            return;
        }
        
        $this->info("正在创建 [{$tableName}] 表...");
        
        Schema::create($tableName, function (Blueprint $table) {
            $table->id();
            $table->string('name', 50)->unique()->comment('角色名称');
            $table->string('description')->nullable()->comment('角色描述');
            $table->tinyInteger('status')->default(1)->comment('状态 0:禁用 1:启用');
            $table->timestamps();
            $table->softDeletes();
        });
        
        $endTime = microtime(true);
        $executionTime = round($endTime - $startTime, 2);
        $this->info("表 [{$tableName}] 创建完成，用时: {$executionTime}秒");
    }

    /**
     * 创建权限表
     */
    protected function createPermissionsTable(): void
    {
        $tableName = 'admin_permissions';
        $startTime = microtime(true);
        
        if (Schema::hasTable($tableName)) {
            $this->info("表 [{$tableName}] 已存在，跳过创建");
            return;
        }
        
        $this->info("正在创建 [{$tableName}] 表...");
        
        Schema::create($tableName, function (Blueprint $table) {
            $table->id();
            $table->string('name', 50)->comment('权限名称');
            $table->string('slug', 50)->unique()->comment('权限标识');
            $table->string('http_method', 255)->nullable()->comment('HTTP方法');
            $table->string('http_path', 255)->nullable()->comment('HTTP路径');
            $table->string('description')->nullable()->comment('权限描述');
            $table->timestamps();
            $table->softDeletes();
        });
        
        $endTime = microtime(true);
        $executionTime = round($endTime - $startTime, 2);
        $this->info("表 [{$tableName}] 创建完成，用时: {$executionTime}秒");
    }

    /**
     * 创建角色权限关联表
     */
    protected function createRolePermissionsTable(): void
    {
        $tableName = 'admin_role_permissions';
        $startTime = microtime(true);
        
        if (Schema::hasTable($tableName)) {
            $this->info("表 [{$tableName}] 已存在，跳过创建");
            return;
        }
        
        $this->info("正在创建 [{$tableName}] 表...");
        
        Schema::create($tableName, function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('role_id')->comment('角色ID');
            $table->unsignedBigInteger('permission_id')->comment('权限ID');
            $table->timestamps();

            $table->foreign('role_id')->references('id')->on('admin_roles')->onDelete('cascade');
            $table->foreign('permission_id')->references('id')->on('admin_permissions')->onDelete('cascade');
            
            $table->unique(['role_id', 'permission_id']);
        });
        
        $endTime = microtime(true);
        $executionTime = round($endTime - $startTime, 2);
        $this->info("表 [{$tableName}] 创建完成，用时: {$executionTime}秒");
    }

    /**
     * 创建管理员角色关联表
     */
    protected function createRoleUsersTable(): void
    {
        $tableName = 'admin_role_users';
        $startTime = microtime(true);
        
        if (Schema::hasTable($tableName)) {
            $this->info("表 [{$tableName}] 已存在，跳过创建");
            return;
        }
        
        $this->info("正在创建 [{$tableName}] 表...");
        
        Schema::create($tableName, function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('role_id')->comment('角色ID');
            $table->unsignedBigInteger('user_id')->comment('管理员ID');
            $table->timestamps();

            $table->foreign('role_id')->references('id')->on('admin_roles')->onDelete('cascade');
            $table->foreign('user_id')->references('id')->on('admin')->onDelete('cascade');
            
            $table->unique(['role_id', 'user_id']);
        });
        
        $endTime = microtime(true);
        $executionTime = round($endTime - $startTime, 2);
        $this->info("表 [{$tableName}] 创建完成，用时: {$executionTime}秒");
    }

    /**
     * 创建管理员会话表
     */
    protected function createSessionsTable(): void
    {
        $tableName = 'admin_sessions';
        $startTime = microtime(true);
        
        if (Schema::hasTable($tableName)) {
            $this->info("表 [{$tableName}] 已存在，跳过创建");
            return;
        }
        
        $this->info("正在创建 [{$tableName}] 表...");
        
        Schema::create($tableName, function (Blueprint $table) {
            $table->string('id')->primary();
            $table->unsignedBigInteger('user_id')->nullable()->index();
            $table->string('ip_address', 45)->nullable();
            $table->text('user_agent')->nullable();
            $table->longText('payload');
            $table->integer('last_activity')->index();
            
            $table->foreign('user_id')->references('id')->on('admin')->onDelete('cascade');
        });
        
        $endTime = microtime(true);
        $executionTime = round($endTime - $startTime, 2);
        $this->info("表 [{$tableName}] 创建完成，用时: {$executionTime}秒");
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        $tables = [
            'admin_sessions',
            'admin_role_users',
            'admin_role_permissions',
            'admin_permissions',
            'admin_roles',
            'admin'
        ];
        
        foreach ($tables as $table) {
            $this->info("正在删除 [{$table}] 表...");
            Schema::dropIfExists($table);
            $this->info("表 [{$table}] 已删除");
        }
    }
};
